package springboot.rabbit.springbootrabbit;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Arat.Wu on 2018/05/30.
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class AddInfoQueue {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static Executor executor2 = Executors.newFixedThreadPool(10);
    private static ExecutorService executor1 = Executors.newFixedThreadPool(10);


    //private static Executor executor1 = new ThreadPoolTaskExecutor();
    //private static Executor executor3 = new ThreadPoolExecutor();

    private class Task implements Runnable{
        @Override
        public void run () {
            for(int i=0;i<1000;i++) {
                System.out.println(Thread.currentThread().getName()+"--"+i);
                //amqpTemplate.convertAndSend("my",Thread.currentThread().getName()+"--"+i);
                rabbitTemplate.convertAndSend("my",Thread.currentThread().getName()+"--"+i);
            }
        }
    }

    @Test
    public void addmy() throws InterruptedException {
        List<ListenableFuture<?>> futures = Lists.newArrayList();
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executor1);
        for (int i = 0; i < 100; i++) {
            futures.add(listeningExecutorService.submit(new Task()));
        }
        final ListenableFuture<List<Object>> resultsFuture = Futures.successfulAsList(futures);

        //Thread.sleep(3000);
        try {//所有都执行完毕
            resultsFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("操作完毕");
            executor1.shutdown();
        }


    }
}
